from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.views.generic import ListView
from django.contrib import messages

from .forms import *
from .models import *
from django.contrib.auth.views import auth_login, auth_logout
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.core.signing import TimestampSigner,BadSignature,SignatureExpired
from user.util.encreay_decreay import SaltedB64Cipher
from user.util.genpass import diceware


@login_required
def center(request):
    if request.method == 'POST':
        cuif = UserInfoChangeForm(data=request.POST, files=request.FILES)
        if cuif.is_valid():
            # 更新用户信息
            if 'username' in cuif.cleaned_data:
                request.user.username = cuif.cleaned_data['username']
            if 'head' in cuif.cleaned_data and cuif.cleaned_data['head']:
                request.user.head = cuif.cleaned_data['head']
            request.user.save()
            messages.success(request, '用户信息更新成功!')
            return redirect(reverse('user:center'))
        else:
            # 表单验证失败，重新显示表单和错误
            cuif = UserInfoChangeForm(initial={
                "username": request.user.username
            })
            return render(request, 'user/center.html', {'form': cuif})
    else:
        cuif = UserInfoChangeForm(initial={
            "username": request.user.username
        })
        return render(request, 'user/center.html', {'form': cuif})

def change_password(request):
    if request.method == 'POST':
        cgf = UserPassWordChangeForm(request.POST)
        if cgf.is_valid():
            if request.user.check_password(cgf.cleaned_data['old_password']):
                request.user.set_password(cgf.cleaned_data['password'])
                request.user.save()

                # 修改密码从新登录
                auth_logout(request)
                return redirect(reverse('user:login'))


            else:
                cgf.add_error("old_password", "原始密码不正确")
                return render(request, 'user/change_password.html', {"form": cgf})
        else:
            return render(request, 'user/change_password.html', {"form": cgf})
    else:
        cgf = UserPassWordChangeForm()
        return render(request, 'user/change_password.html', {"form": cgf})

# def change_head(request):
#     if request.method == 'POST':

dec = diceware()

from user.util.yanzheng import send_sms,check_sms


def send_verification_code(request):
    """发送手机验证码"""
    if request.method == 'POST':
        phone = request.POST.get('phone')
        if not phone:
            return JsonResponse({'success': False, 'msg': '手机号不能为空'})
        
        # 验证手机号格式
        import re
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return JsonResponse({'success': False, 'msg': '手机号格式不正确'})
        
        # 调用验证码发送函数
        result = send_sms(phone)
        return JsonResponse(result)
    return JsonResponse({'success': False, 'msg': '请求方式错误'})

def register(request):
    if request.method == "POST":
        print('原始数据',request.POST)
        rf = UserRegisterForm(request.POST)
        print('表单数据',rf.data)
        # print(rf.is_valid())
        phone = request.POST.get('phone')
        code = request.POST.get('code')
        
        if not (phone and code):
            rf.add_error('phone', '手机号和验证码不能为空')
            return render(request, 'user/register.html', {"form": rf})

        # 验证手机验证码
        ck = check_sms(phone, code)
        if not ck['success']:
            # 验证码错误，返回表单和错误信息
            return render(request, 'user/register.html', {"form": rf, "phone_error": ck['msg']})
        print('开始表单验证...')
        if rf.is_valid():
            user = CustomUser(
                username=rf.cleaned_data['phone'],
                is_active=True
            )
            user.set_password(rf.cleaned_data['password'])
            user.save()
            # 注册成功后自动登录
            auth_login(request, user)
            messages.success(request, '注册成功！')
            return redirect(reverse('main:index'))
        else:
            return render(request, 'user/register.html', {"form": rf})
    else:
        rf = UserRegisterForm()
        return render(request, 'user/register.html', {"form": rf})

def logout(request):
    auth_logout(request)
    return redirect(reverse('user:login'))
def login(request):
    if request.method == "POST":
        lf = UserLoginForm(request.POST)
        if lf.is_valid():
            user = CustomUser.objects.filter(username=lf.cleaned_data['username']).first()
            if user:
                if user.check_password(lf.cleaned_data['password']):
                    if user.is_active:
                        auth_login(request, user)
                        if request.GET.get("next"):
                            return redirect(request.GET.get("next"))
                        else:
                            return redirect(reverse('main:index'))
                    else:
                        lf.add_error("username","该用户未激活")
                        return render(request,'user/login.html',{"form":lf})
                else:
                    lf.add_error("password", "密码错误")
                    return render(request, 'user/login.html', {"form": lf})
            else:
                lf.add_error("username", "用户名不存在")
                return render(request, 'user/login.html', {"form": lf})
        else:
            return render(request, 'user/login.html', {"form": lf})

    else:
        lf = UserLoginForm()
        return render(request, 'user/login.html', {"form": lf})


def active(request ,id):
    try:
        sig_util = TimestampSigner()
        encry_id = sig_util.unsign(id,max_age=settings.ACTION_EMAIL_TIME )
        new_id = SaltedB64Cipher.decrypt(encry_id,dec)
        user = CustomUser.objects.filter(id=new_id).first()
        if user:
            user.is_active= True
            user.save()
            return redirect(reverse('user:login'))
        else:
            return HttpResponse("激活失败")
    except SignatureExpired:
        return HttpResponse("超时，请及时激活")
    except BadSignature:
        return HttpResponse("激活链接错误")
    # except Exception:
    #     return HttpResponse("未知错误")


